import axios from "axios";

import config from "@/config";

import router from "@/router";

import store from "@/store";

import { Message } from "element-ui";

const ErrorMessage = {
    PARAM_ERROR: '参数不正确',
    USER_ACCOUNT_ERROR: '用户账号密码错误',
    USER_LOGIN_ERROR: '用户未登录',
    BUSINESS_ERROR: '业务请求失败',
    AUTH_ERROR: '认证失败或TOKEN过期',
}

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 5000,
})


// 添加请求拦截器
service.interceptors.request.use(function (config) {
    let headers = config.headers
    let token = store.state.token || ''
    if(!headers.Authorization){
        headers.Authorization = 'Bearer ' + token
    }
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});




// 添加响应拦截器
service.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    console.log(response);

    let { code , data , msg } = response.data

    if(code == 200){
        return data
    }else if(code == 10001){
        Message.error({
            message: ErrorMessage.PARAM_ERROR,
            offset: 80
        })
        return Promise.reject(ErrorMessage.PARAM_ERROR)
    }else if(code == 20001){
        Message.error({
            message: ErrorMessage.USER_ACCOUNT_ERROR,
            offset: 80
        })
        return Promise.reject(ErrorMessage.USER_ACCOUNT_ERROR)
        
    }else if(code == 20002){
        Message.error({
            message: ErrorMessage.USER_LOGIN_ERROR,
            offset: 80
        })
        return Promise.reject(ErrorMessage.USER_LOGIN_ERROR)
        
    }else if(code == 30001){
        Message.error({
            message: ErrorMessage.BUSINESS_ERROR,
            offset: 80
        })
        return Promise.reject(ErrorMessage.BUSINESS_ERROR)
        
    }else if(code == 50001){
        Message.error({
            message: ErrorMessage.AUTH_ERROR,
            offset: 80
        })
        setTimeout(()=>{
            router.push('/login')
        }, 1000)
        return Promise.reject(ErrorMessage.AUTH_ERROR)
        
    }else if(code == 40001){
        Message.error({
            message: msg,
            offset: 80
        })
        return Promise.reject(msg)
    }
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});


function request(options){
    options.method = options.method || 'get';
    
    if(options.method.toLowerCase() == 'get'){
        options.params = options.data
    }

    if(config.env == 'production'){
        service.defaults.baseURL = config.baseApi
    }else{
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }

    return service(options)
}


['get', 'post', 'delete', 'put', 'patch'].forEach((item)=>{
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})


export default request